package com.liliudong.cursormate.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liliudong.cursormate.common.R;
import com.liliudong.cursormate.common.exception.BusinessException;
import com.liliudong.cursormate.entity.SysPermission;
import com.liliudong.cursormate.service.SysPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 系统权限控制器
 *
 * @author Liudong.li
 * @version 1.0
 * @project cursor-mate
 * @date 2023/10/25 11:32:16
 */
@RestController
@RequestMapping("/v1/sys-permission")
@RequiredArgsConstructor
public class SysPermissionController {

    private final SysPermissionService sysPermissionService;

    /**
     * 创建
     *
     * @param sysPermission sys权限
     * @return {@link R}<{@link ?}>
     */
    @PostMapping
    @SaCheckPermission("sys:per:add")
    public R<?> create(@RequestBody SysPermission sysPermission) {
        long count = sysPermissionService.count(
                Wrappers.lambdaQuery(SysPermission.class)
                        .eq(SysPermission::getPermission, sysPermission.getPermission())
        );
        if (count > 0) {
            throw new BusinessException("权限标识符不能重复");
        }
        sysPermissionService.save(sysPermission);
        return R.success();
    }

    /**
     * 根据ID删除
     *
     * @param id id
     * @return {@link R}<{@link ?}>
     */
    @DeleteMapping("/{id}")
    @SaCheckPermission("sys:per:del")
    public R<?> del(@PathVariable Long id) {
        sysPermissionService.removeById(id);
        return R.success();
    }

    /**
     * 更新
     *
     * @param sysPermission sys权限
     * @return {@link R}<{@link ?}>
     */
    @PutMapping
    @SaCheckPermission("sys:per:edit")
    public R<?> update(@RequestBody SysPermission sysPermission) {
        sysPermissionService.updateById(sysPermission);
        return R.success();
    }

    /**
     * 分页查询
     *
     * @param page     页
     * @param pageSize 页面大小
     * @return {@link R}<{@link ?}>
     */
    @GetMapping("/page")
    @SaCheckPermission("sys:per:page")
    public R<?> page(@RequestParam(defaultValue = "1") Long page,
                     @RequestParam(defaultValue = "10") Long pageSize) {
        Page<SysPermission> sysPermissionPage = sysPermissionService.page(Page.of(page, pageSize));
        return R.success(sysPermissionPage);
    }

    /**
     * 查询详情
     *
     * @param id id
     * @return {@link R}<{@link ?}>
     */
    @GetMapping("/{id}")
    @SaCheckPermission("sys:per:info")
    public R<?> query(@PathVariable Long id) {
        return R.success(sysPermissionService.getById(id));
    }
}
